package com.thirdgroup.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.thirdgroup.controller.base.BaseServlet;
import com.thirdgroup.pojo.entity.Permission;
import com.thirdgroup.service.ManagerInfoService;
import com.thirdgroup.service.impl.ManagerInfoServiceImpl;
import com.thirdgroup.utils.RegexUtils;
import com.thirdgroup.utils.respond.R;
import com.thirdgroup.utils.respond.ResponseUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@WebServlet("/managerinfo/*")
public class ManagerInfoServlet extends BaseServlet {
    private ManagerInfoService InfoService = new ManagerInfoServiceImpl();
    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String login_name = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(login_name);
        System.out.println(password);
        // 获取用户提交的验证码
        String userCaptcha = request.getParameter("captcha").toLowerCase();
        HttpSession session = request.getSession();
        String serverCaptcha = (String) session.getAttribute("serverVerCode");

        // 校验验证码
        if (!userCaptcha.equals(serverCaptcha)) {
            System.out.println("验证码错误！！");
            response.getWriter().write(JSONObject.toJSONString(R.error(500,"验证码错误！！")));
            response.getWriter().flush();
            response.getWriter().close();
            return;
        }
//        response.setContentType("application/json;charset=utf-8");
        //1.验证验证码是否正确
        //输入框输入的验证码值
//        String vercode = request.getParameter("vercode");
//        System.out.println("vercode======"+vercode);
//        //获取session域中获取生成验证码
//        String serverVerCode = request.getSession().getAttribute("serverVerCode").toString();
//
//        System.out.println("serverVerCode====="+serverVerCode);
//        if(!serverVerCode.equalsIgnoreCase(vercode)){
//            System.out.println("验证码错误！！");
//            response.getWriter().write(JSONObject.toJSONString(R.error(500,"验证码错误！！")));
//            response.getWriter().flush();
//            response.getWriter().close();
//            return;
//        }else{
            //正确
            //2.用户名和密码是否正确
            //获取输入框用户名和密码值
            // 进行后端参数校验
            if(!RegexUtils.find(login_name,"^[a-zA-Z][a-zA-Z0-9_]{1,15}$")){
                response.getWriter().write(JSONObject.toJSONString(R.error(500,"允许2-10字符，允许汉字字母数字下划线")));
                response.getWriter().flush();
                response.getWriter().close();
                return;
            }
            if(!RegexUtils.find(password,"^[a-zA-Z0-9]\\w{5,17}$")){
                response.getWriter().write(JSONObject.toJSONString(R.error(500,"密码以字母开头，长度在6~18之间，只能包含字母、数字和下划线")));
                response.getWriter().flush();
                response.getWriter().close();
                return;
            }
//        }
        // 代码能走到这里，表示：参数校验是通过的

        System.out.println("login before");
        R result = InfoService.Login(login_name, password);
        System.out.println("login after");
        System.out.println("result======"+result);
        System.out.println("result.getCode()="+result.getCode()+"---------result.getMsg()="+result.getMessage());
        response.getWriter().write(JSONObject.toJSONString(result));
        response.getWriter().flush();
        response.getWriter().close();


    }
    public void managerinfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        String uid = request.getParameter("uid");
        System.out.println("uid-->"+uid);
        List<Permission> rbac = InfoService.rbac(uid);
        for (Permission permission : rbac) {
            System.out.println("permission--->"+permission);
        }

        List< Map > treeList = new ArrayList<>();
        Map module = null;
        for(Permission node : rbac){
            if(node.getType() == 1){
                module = new LinkedHashMap();
                module.put("node", node);
                module.put("children", new ArrayList());
                treeList.add(module);
            }else if(node.getType() == 2){
                List children = (List)module.get("children");
                children.add(node);
            }
        };
        for (Map map : treeList) {
            map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
        }
        String json = new ResponseUtils()
                .put("nodeList", treeList).toJsonString();
        System.out.println(json);
        response.getWriter().println(json);
        response.getWriter().flush();
        response.getWriter().close();

    }
    public void queryAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        R r = InfoService.selectAll();
        System.out.println("获取了管理员列表数据  ");
        System.out.println(r.getData());
        response.getWriter().write(JSONObject.toJSONString(r));
        response.getWriter().flush();
        response.getWriter().close();
    }
    public void updateStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        // 从请求体中获取 JSON 字符串
        BufferedReader reader = request.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        String json = jsonBuilder.toString();

        // 使用 ObjectMapper 将 JSON 字符串转换为 Map 对象
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> data = objectMapper.readValue(json, new TypeReference<Map<String, String>>() {});

        // 获取客户ID和状态参数值
        String managerId = data.get("managerId");
        String status = data.get("status");
        System.out.println("managerId=="+managerId);
        System.out.println("status=="+status);
        // 创建当前日期对象
        Date date = new Date();

        // 创建 SimpleDateFormat 对象，指定日期时间格式
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 使用 SimpleDateFormat 格式化日期时间
        String formattedDate = formatter.format(date);
        R r = InfoService.updateState(managerId, status,formattedDate);
        response.getWriter().write(JSONObject.toJSONString(r));
        response.getWriter().flush();
        response.getWriter().close();
    }
    public void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        // 从请求体中获取 JSON 字符串
        BufferedReader reader = request.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        String json = jsonBuilder.toString();

        // 使用 ObjectMapper 将 JSON 字符串转换为 Map 对象
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> data = objectMapper.readValue(json, new TypeReference<Map<String, String>>() {});

        // 获取客户ID和状态参数值
        String username = data.get("username");
        String password = data.get("password");
        String profilePicture = data.get("profilePicture");
        System.out.println("username=="+username);
        System.out.println("password=="+password);
        System.out.println("profilePicture=="+profilePicture);
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 定义时间格式化器，用于格式化日期时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        // 格式化当前时间
        String formattedDateTime = now.format(formatter);
        // 将格式化后的时间字符串添加前缀
        String id = "M" + formattedDateTime;
        System.out.println(id);
        // 创建当前日期对象
        Date date = new Date();
        // 创建 SimpleDateFormat 对象，指定日期时间格式
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 使用 SimpleDateFormat 格式化日期时间
        String formattedDate = formatter2.format(date);
        R r = InfoService.add(id,username,password,formattedDate,profilePicture);
        response.getWriter().write(JSONObject.toJSONString(r));
        response.getWriter().flush();
        response.getWriter().close();
    }
    public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        // 从请求体中获取 JSON 字符串
        BufferedReader reader = request.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        String json = jsonBuilder.toString();

        // 使用 ObjectMapper 将 JSON 字符串转换为 Map 对象
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> data = objectMapper.readValue(json, new TypeReference<Map<String, String>>() {});

        // 获取ID
        String managerid = data.get("managerId");
//        String managerid1 = request.getParameter("managerId");
        System.out.println("根据id删除管理员");
        System.out.println("managerid=="+managerid);
//        System.out.println("managerid1=="+managerid1);

        R r = InfoService.delete(managerid);
        response.getWriter().write(JSONObject.toJSONString(r));
        response.getWriter().flush();
        response.getWriter().close();
    }
    public void detail(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        // 从请求体中获取 JSON 字符串
        BufferedReader reader = request.getReader();
        StringBuilder jsonBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            jsonBuilder.append(line);
        }
        String json = jsonBuilder.toString();

        // 使用 ObjectMapper 将 JSON 字符串转换为 Map 对象
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, String> data = objectMapper.readValue(json, new TypeReference<Map<String, String>>() {});

        // 获取ID
        String managerid = data.get("managerid");
        String managerid1 = request.getParameter("managerid");
        System.out.println("根据id查看管理员");
        System.out.println("managerid=="+managerid);
        System.out.println("managerid1=="+managerid1);

        R r = InfoService.detail(managerid);
        System.out.println("根据id查找到数据如下：");
        System.out.println(r.getData());
        response.getWriter().write(JSONObject.toJSONString(r));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
